﻿using Domain.Context;
using Domain.Provider;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using WebUI.Models;

namespace ManagerHoursTool.Controllers
{
    public class DistrictController : Controller
    {
        private IDataProvider<ManagerHours> _managerRepository;

        public DistrictController(IDataProvider<ManagerHours> repository)
        {
            _managerRepository = repository;
        }

        public ActionResult Index(int districtId)
        {
            var entities = _managerRepository.Entities.ToList().Select(x => x.District).Distinct();
            ViewBag.districtId = districtId;
            return View("Index", GetGridModel(districtId));
        }

        public ActionResult Edit(int districtId)
        {
            return PartialView("_districtEditGridPartial", GetGridModel(districtId));
        }

        public ActionResult Approve(StoreManagerModel storeManagerModel, int districtId)
        {
            ManagerHours entity = GetEntity(storeManagerModel);
            entity.Approved = true;
            _managerRepository.SaveEntity(entity, User);

            return RedirectToActionPermanent("Edit", new { districtId = districtId });
        }

        public ActionResult Save(StoreManagerModel storeManagerModel, int districtId)
        {            
            ManagerHours entity = GetEntity(storeManagerModel);
            entity.DaysWorked = storeManagerModel.DaysWorked;
            entity.DaysSick = storeManagerModel.DaysSick;
            entity.DaysVacation = storeManagerModel.DaysVacation;
            entity.DaysOther = storeManagerModel.DaysOff;
            entity.Approved = storeManagerModel.Approved;
            _managerRepository.SaveEntity(entity, User);

            return PartialView("_districtGridPartialView", GetGridModel(districtId));
        }

        private IEnumerable<StoreManagerModel> GetGridModel(int id)
        {
            IEnumerable<ManagerHours> data = GetDistrictsById(id);
            List<StoreManagerModel> model = new List<StoreManagerModel>();
            foreach (var entity in data)
            {
                model.Add(new StoreManagerModel(entity));
            }
            return model;
        }

        private IEnumerable<ManagerHours> GetDistrictsById(int districtId)
        {
            var models = _managerRepository.Entities.ToList().Where(x => x.District == districtId);
            return models;
        }

        private ManagerHours GetEntity(StoreManagerModel model)
        {
            var lala = model.Name;
            var entity = (ManagerHours) _managerRepository.Entities.ToList().First(x => x.Name == model.Name);
            return entity;
        }
    }
}
